﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace MSMQ试用
{
    /// <summary>
    /// msmq自定义序列化
    /// 字节数组序列化
    /// http://www.cnblogs.com/smark/archive/2013/05/31/3110208.html
    /// </summary>
    public class BytesFormatter : IMessageFormatter
    {
        public bool CanRead(Message message)
        {
            return message.BodyStream != null && message.BodyStream.Length > 0;
        }

        public object Clone()
        {
            return this;
        }

        /// <summary>
        /// 返回数据
        /// </summary>
        /// <param name="message">数据信息</param>
        /// <returns></returns>
        public object Read(Message message)
        {

            byte[] arr = new byte[message.BodyStream.Length];

            message.BodyStream.Read(arr, 0, arr.Length);
            //释放
            message.BodyStream.Close();
            return arr;


        }

        public void Write(Message message, object obj)
        {
            byte[] arr = (byte[])obj;
            message.BodyStream = new System.IO.MemoryStream(arr);

        }
    }
    /// <summary>
    /// ProtoBuf自定义序列化
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ProtobufFormater<T> : IMessageFormatter
    {
        public bool CanRead(Message message)
        {
            return message.BodyStream != null && message.BodyStream.Length > 0;
        }

        public object Read(Message message)
        {
            return ProtoBuf.Meta.RuntimeTypeModel.Default.Deserialize(message.BodyStream, null, typeof(T));
        }

        [System.ThreadStatic]
        private static System.IO.MemoryStream mStream;

        public void Write(Message message, object obj)
        {
            if (mStream == null)
                mStream = new System.IO.MemoryStream(4096);
            mStream.Position = 0;
            mStream.SetLength(0);
            ProtoBuf.Meta.RuntimeTypeModel.Default.Serialize(mStream, obj);
            message.BodyStream = mStream;
        }

        public object Clone()
        {
            return this;
        }

    }
}
